/*
 * @Description:
 * @Author: ZY
 * @Date: 2021-01-08 17:56:34
 * @LastEditors: ZY
 * @LastEditTime: 2021-01-08 19:01:43
 */
 // Parse the time to string
// 自定义时间过滤器
export const Time_filter = (
    time?: object | string | number | null,
    cFormat?: string
): string | null => {
    if (time === undefined || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s} {a}'
    let date: Date
    if (typeof time === 'object') {
        date = time as Date
    } else {
        if (typeof time === 'string') {
            if (/^[0-9]+$/.test(time)) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj: { [key: string]: number } = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][value]
        }
        return value.toString().padStart(2, '0')
    })
    return timeStr
}

/**
 * 格式为
 *  {
 *  "page": 1,
 *  "size": 15,
 *  "param": {
		  name: '',
      sex: ''
 		}
 *	}
 */
export const utilsQQCS = (e: any) => {
  let dataCopy = JSON.parse(JSON.stringify(e))
  for (let i in e.param) {
    e.param[i].replace(/(^\s*)|(\s*$)/g, '') !== ''
      ? (dataCopy.param[`has_${i}`] = true)
      : (dataCopy.param[`has_${i}`] = false)
  }
  return dataCopy
}


// Format and filter json data using filterKeys array
export const formatJson = (filterKeys: any, jsonData: any) =>
    jsonData.map((data: any) => filterKeys.map((key: string) => {
        if (key === 'timestamp') {
            return Time_filter(data[key])
        } else {
            return data[key]
        }
    }))

// Check if an element has a class
export const hasClass = (ele: HTMLElement, className: string) => {
    return !!ele.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

// Add class to element
export const addClass = (ele: HTMLElement, className: string) => {
    if (!hasClass(ele, className)) ele.className += ' ' + className
}

// Remove class from element
export const removeClass = (ele: HTMLElement, className: string) => {
    if (hasClass(ele, className)) {
        const reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
        ele.className = ele.className.replace(reg, ' ')
    }
}

// Toggle class for the selected element
export const toggleClass = (ele: HTMLElement, className: string) => {
    if (!ele || !className) {
        return
    }
    let classString = ele.className
    const nameIndex = classString.indexOf(className)
    if (nameIndex === -1) {
        classString += '' + className
    } else {
        classString =
            classString.substr(0, nameIndex) +
            classString.substr(nameIndex + className.length)
    }
    ele.className = classString
}

// export const dateToMs = (date: string)=>{
//     let date = new Date(date).getTime();
//     return date
// }

// 快速排序
export const quickSort=(array:any , start:any, end:any):any=> {
	// console.log('--------------',array)
  let length = array.length;

  // 如果不是数组或者数组长度小于等于1，直接返回，不需要排序 
  if (!Array.isArray(array) || length <= 1 || start >= end) 
	return array;

  let index = partition(array, start, end); // 将数组划分为两部分，并返回右部分的第一个元素的索引值

  quickSort(array, start, index - 1); // 递归排序左半部分
  quickSort(array, index + 1, end); // 递归排序右半部分
}


function partition(array:any, start:any, end:any) {

  let pivot = array[start]; // 取第一个值为枢纽值，获取枢纽值的大小


  // 当 start 等于 end 指针时结束循环
  while (start < end) {

    // 当 end 指针指向的值大等于枢纽值时，end 指针向前移动
    while (array[end] >= pivot && start < end) {
      end--;
    }

    // 将比枢纽值小的值交换到 start 位置
    array[start] = array[end];

    // 移动 start 值，当 start 指针指向的值小于枢纽值时，start 指针向后移动
    while (array[start] < pivot && start < end) {
      start++;
    }

    // 将比枢纽值大的值交换到 end 位置，进入下一次循环
    array[end] = array[start];
  }

  // 将枢纽值交换到中间点
  array[start] = pivot;

  // 返回中间索引值
  return start;
}

//insertStr 字符串定标插入
export const insertStr=(str?:string, start:any, newStr:any):any=>{
	str = String(str)
  return str.slice(0, start) + newStr + str.slice(start);
}